package com.lqk.channel.socket.datagramchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;

public class DatagramChannelDemo2 {
    //接收的实现
    public static void main(String[] args) throws Exception {
        //打开 DatagramChannel
        DatagramChannel receiveChannel = DatagramChannel.open();
        InetSocketAddress receiveAddress=new InetSocketAddress(9999);

        //绑定
        receiveChannel.bind(receiveAddress);

        //创建 buffer
        ByteBuffer receiveBuffer=ByteBuffer.allocate(1024);

        //接收
        while (true){
            receiveBuffer.clear();
            SocketAddress socketAddress = receiveChannel.receive(receiveBuffer);

            receiveBuffer.flip();//模式转换

            System.out.println(socketAddress.toString());

            System.out.println(Charset.forName("UTF-8").decode(receiveBuffer));

        }

    }
}
